#!/bin/sh
#VER_NUM=`cat /etc/issue | grep -iE "Ubuntu 1(5|6|7|8|9)\.|Debian GNU/Linux (9|10|11)|Pardus GNU/Linux " | wc -l` ;
#VER_NUM2=`lsb_release -a | grep Description | grep -iE "Ubuntu 1(5|6|7|8|9)\.|Debian GNU/Linux (9|10|11)|Pardus GNU/Linux " | wc -l`
DWT_INSTALL_PATH="/opt/dynamsoft/Dynamic Web TWAIN Service 19"
mkdir -p "${DWT_INSTALL_PATH}/cache"
mkdir -p "${DWT_INSTALL_PATH}/dump"
mkdir -p "${DWT_INSTALL_PATH}/log"
mkdir -p "${DWT_INSTALL_PATH}/upload"

find "${DWT_INSTALL_PATH}/cache" -type d -exec chmod 777 {} \;
find "${DWT_INSTALL_PATH}/cache" -type f -exec chmod 666 {} \;
find "${DWT_INSTALL_PATH}/dump" -type d -exec chmod 777 {} \;
find "${DWT_INSTALL_PATH}/dump" -type f -exec chmod 666 {} \;
find "${DWT_INSTALL_PATH}/log" -type d -exec chmod 777 {} \;
find "${DWT_INSTALL_PATH}/log" -type f -exec chmod 666 {} \;
find "${DWT_INSTALL_PATH}/upload" -type d -exec chmod 777 {} \;
find "${DWT_INSTALL_PATH}/upload" -type f -exec chmod 666 {} \;

#start service
while :
do
PROCESS_NUM=`ps aux | grep "${DWT_INSTALL_PATH}/DynamicWebTWAINService" | grep -v "grep"| grep -v "DSUpdate" | grep -v "DynamsoftScanning" | grep -v "Mgr" | grep -v "scan"| grep -v "cert"| grep -v "defunct"| grep -v ".deb" | wc -l` 
if [ $PROCESS_NUM -eq 0 ]; then
	"${DWT_INSTALL_PATH}/DynamicWebTWAINService"&
fi
if [ -d "${DWT_INSTALL_PATH}/cache" ]; then
	find "${DWT_INSTALL_PATH}/cache" -type d -exec chmod 777 {} \;
	find "${DWT_INSTALL_PATH}/cache" -type f -exec chmod 666 {} \;
fi
if [ -d "${DWT_INSTALL_PATH}/dump" ]; then
	find "${DWT_INSTALL_PATH}/dump" -type d -exec chmod 777 {} \;
	find "${DWT_INSTALL_PATH}/dump" -type f -exec chmod 666 {} \;
fi
if [ -d "${DWT_INSTALL_PATH}/log" ]; then
	find "${DWT_INSTALL_PATH}/log" -type d -exec chmod 777 {} \;
	find "${DWT_INSTALL_PATH}/log" -type f -exec chmod 666 {} \;
fi
if [ -d "${DWT_INSTALL_PATH}/upload" ]; then
	find "${DWT_INSTALL_PATH}/upload" -type d -exec chmod 777 {} \;
	find "${DWT_INSTALL_PATH}/upload" -type f -exec chmod 666 {} \;
fi

DUMP_NUM=0
if [ -d /var/crash ]; then
	DUMP_NUM=`ls /var/crash | grep DynamicWebTWAINService | wc -l`
fi
if [ $DUMP_NUM -ne 0 ]; then
	mv /var/crash/*DynamicWebTWAINService* "${DWT_INSTALL_PATH}/dump"
fi


sleep 2s
done

